﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using org.googlecoders.GetLatestChromium.Properties;

namespace org.googlecoders.GetLatestChromium
{
	public partial class SettingsForm : Form
	{
		public SettingsForm()
		{
			InitializeComponent();
		}

		private void SettingsForm_Load(object sender, EventArgs e)
		{
			IntervalDropDown.Items.Add(new Interval{Name="1 Hour",Hours=1});
			IntervalDropDown.Items.Add(new Interval{Name="3 Hours",Hours=3});
			IntervalDropDown.Items.Add(new Interval{Name="6 Hours",Hours=6});
			IntervalDropDown.Items.Add(new Interval{Name="12 Hours",Hours=12});
			IntervalDropDown.Items.Add(new Interval{Name="1 Day",Hours=24});
			IntervalDropDown.Items.Add(new Interval{Name="1 Week",Hours=24*7});
			IntervalDropDown.Items.Add(new Interval{Name="4 Weeks",Hours=24*7*4});
			IntervalDropDown.Items.Add(new Interval{Name="12 Weeks",Hours=24*7*12});
			for(int i = 0; i<IntervalDropDown.Items.Count;++i)
			{
				if(((Interval)IntervalDropDown.Items[i]).Hours == Settings.Default.Interval)
				{
					IntervalDropDown.SelectedIndex = i;
					break;
				}
			}
			if(IntervalDropDown.SelectedIndex < 0)
				IntervalDropDown.SelectedIndex = 0;


			List<BuildLocation> sources = BuildLocation.GetLocations();
			foreach(BuildLocation l in sources)
			{
				SourceDropDown.Items.Add(l.Name);
			}
			for (int i = 0; i < SourceDropDown.Items.Count; ++i)
			{
				if ((string)SourceDropDown.Items[i] == Settings.Default.Source)
				{
					SourceDropDown.SelectedIndex = i;
					break;
				}
			}
			if (SourceDropDown.SelectedIndex < 0)
				SourceDropDown.SelectedIndex = 0;
		}
		
		public class Interval
		{
			public string Name;
			public int Hours;
			public override string ToString()
			{
				return Name;
			}
		}

		private void OKButton_Click(object sender, EventArgs e)
		{
			Settings.Default.Interval = ((Interval)IntervalDropDown.SelectedItem).Hours;
			if(Settings.Default.Source != (string)SourceDropDown.SelectedItem)
			{
				Settings.Default.OurBuild = 0;
				Settings.Default.OurRevision = 0;
			}
			Settings.Default.Source = (string)SourceDropDown.SelectedItem;
			Settings.Default.NextCheck = Settings.Default.LastCheck.AddHours(Settings.Default.Interval);
			Settings.Default.Save();
		}

		private void CancelButton_Click(object sender, EventArgs e)
		{
			Settings.Default.Reload();
		}

		private void ConfigFileButton_Click(object sender, EventArgs e)
		{
			string file = BuildLocation.ExportLocations();
			if(!string.IsNullOrEmpty(file))
				MessageBox.Show("Source configurations saved to " + file, "Success");
			else
				MessageBox.Show("Export failed.");
		}
	}
}
